package com.xiaozeng.user.shiro;

import com.xiaozeng.constants.UserConstants;
import com.xiaozeng.pojo.User;
import com.xiaozeng.user.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @Author: xiaozeng
 * @Date: 2022 11
 * @Description: 自定义授权和认证
 **/
@Component
public class MyRealm extends AuthorizingRealm {
    @Autowired
    private UserService userService;
    //自定义授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("授权");
        return null;
    }
    //自定义认证，shiro的Login方法底层会调用这个
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //1获取用户身份信息
        UsernamePasswordToken userToken = (UsernamePasswordToken) token;
        //2.调用业务层获取用户信息（数据库）
        User user = userService.getById(userToken.getUsername());
        //非空判断
        if(user==null){
            return null;
        }
        //3，将数据封装返回
        System.out.println("认证");
        //密码认证，shiro做
        //user对象，数据库中的密码，盐值，RealmName：当前Realm对象的name,调用父类的getName()方法即可.
        return new SimpleAuthenticationInfo(
                user,user.getPassword(), ByteSource.Util.bytes(UserConstants.USER_SLAT),this.getName());
    }
}
